<script setup lang="ts">
const inputValue = defineModel<string>({ required: true })

const tanpanchaStore = useTanpanchaStore()
const value = ref('')
const showDropdown = ref(false)
const options = computed(() => {
  return tanpanchaStore.emissionSourceOptions
})

const filteredOptions = computed(() => {
  return options.value.filter(item =>
    inputValue.value === undefined || inputValue.value === '' || item.label.toLowerCase().includes(inputValue.value.toLowerCase()),
  )
})

function handleInput(query: string) {
  inputValue.value = query
  showDropdown.value = true
}

function handleBlur() {
  setTimeout(() => {
    showDropdown.value = false
  }, 200) // 延迟关闭以允许点击选项
}

function selectOption(item: any) {
  value.value = item.value
  inputValue.value = item.label
  showDropdown.value = false
}
</script>

<template>
  <div class="custom-select">
    <el-input
      v-model="inputValue"
      clearable
      placeholder="请选择或输入排放源"
      @input="handleInput"
      @focus="showDropdown = true"
      @blur="handleBlur"
    />
    <div v-show="showDropdown" class="custom-dropdown">
      <div
        v-for="item in filteredOptions"
        :key="item.value"
        class="custom-option"
        @mousedown="selectOption(item)"
      >
        {{ item.label }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.custom-select {
  position: relative;
  width: 240px;
}

.custom-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  background: var(--el-bg-color);
  z-index: 2000;
  max-height: 200px;
  overflow-y: auto;
}

.custom-option {
  padding: 4px 12px;
  cursor: pointer;
  font-size: 14px;
}

.custom-option:hover {
  background-color: var(--el-fill-color-light);
}
</style>
